<template>
    <div class="app-container" style="padding: 20px">
        <el-card>
            <FormTopBar
                :title="topTitle"
                :flowInsId="form.flowInsId"
                :taskId="taskId"
                :businessId="form.id"
                :billType="form.billType"
                :readonly="readonly"
                @submitForm="submitForm"
            ></FormTopBar>
        </el-card>
        <el-form
            ref="form"
            :model="form"
            :rules="readonly ? '' : rules"
            label-width="120px"
            :disabled="readonly"
        >
            <el-card class="top15">
                <el-col :xs="24" :sm="12" :md="8" :lg="8">
                    <el-form-item
                        label="姓名"
                        prop="changerNickName"
                        :rules="
                            readonly || $route.params.formId
                                ? []
                                : [
                                      {
                                          required: true,
                                          message: '姓名不能为空',
                                          trigger: 'change',
                                      },
                                  ]
                        "
                    >
                        <el-input
                            :disabled="!!$route.params.formId"
                            suffix-icon="el-icon-search"
                            readonly
                            @focus="openSecelctOneUser"
                            v-model="form.changerNickName"
                        />
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="8">
                    <el-form-item label="工号" prop="staffNum">
                        <el-input disabled v-model="form.staffNum" />
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="8">
                    <el-form-item label="性别" prop="sex">
                        <el-select disabled v-model="form.sex" clearable>
                            <el-option
                                v-for="dict in dict.type.sys_user_sex"
                                :key="dict.value"
                                :label="dict.label"
                                :value="dict.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="8">
                    <el-form-item label="出生日期" prop="birthdate">
                        <el-date-picker
                            disabled
                            clearable
                            v-model="form.birthdate"
                            type="date"
                            value-format="yyyy-MM-dd"
                        ></el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="8">
                    <el-form-item label="员工状态" prop="staffType">
                        <el-select disabled v-model="form.staffType">
                            <el-option
                                v-for="dict in dict.type.hrm_staff_type"
                                :key="dict.value"
                                :label="dict.label"
                                :value="dict.value"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="8">
                    <el-form-item label="调前部门" prop="beforeDeptId">
                        <treeselect
                            disabled
                            v-model="form.beforeDeptId"
                            :options="deptOptions"
                            :normalizer="normalizer"
                            placeholder=""
                        />
                    </el-form-item>
                </el-col>

                <el-col :xs="24" :sm="12" :md="8" :lg="8">
                    <el-form-item label="调前岗位" prop="beforePostId">
                        <el-select v-model="form.beforePostId" disabled>
                            <el-option
                                v-for="item in postOptions"
                                :key="item.postId"
                                :label="item.postName"
                                :value="item.postId"
                                :disabled="item.status == 1"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="8">
                    <el-form-item label="调整日期" prop="submitTime">
                        <el-date-picker
                            clearable
                            v-model="form.submitTime"
                            type="date"
                            value-format="yyyy-MM-dd"
                        ></el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="8">
                    <el-form-item label="调后部门" prop="afterDeptId">
                        <treeselect
                            :disabled="readonly"
                            v-model="form.afterDeptId"
                            :options="deptOptions"
                            :normalizer="normalizer"
                            placeholder=""
                        />
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="8">
                    <el-form-item label="岗位类别" prop="postTypeCode">
                        <el-select
                            v-model="form.postTypeCode"
                            @change="getPostData2"
                        >
                            <el-option
                                v-for="dict in dict.type.job_category"
                                :key="dict.value"
                                :label="dict.label"
                                :value="dict.value"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col :xs="24" :sm="12" :md="8" :lg="8">
                    <el-form-item label="调后岗位" prop="afterPostId">
                        <el-select
                            v-model="form.afterPostId"
                            clearable
                            @change="$forceUpdate()"
                        >
                            <el-option
                                v-for="item in postOptions2"
                                :key="item.postId"
                                :label="item.postName"
                                :value="item.postId"
                                :disabled="item.status == 1"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col :xs="24" :sm="24" :md="24" :lg="24">
                    <el-form-item
                        label="调整原因"
                        prop="reason"
                        v-if="$store.getters.allDefectObj['HR-WEB-062'] == 0"
                    >
                        <el-input
                            v-model="form.reason"
                            type="textarea"
                            :rows="5"
                        />
                    </el-form-item>
                    <el-form-item
                        label="调整原因"
                        prop="reason"
                        v-else
                        :rules="
                            $store.getters.allDefectObj['HR-WEB-062'] == 0
                                ? []
                                : [
                                      {
                                          max: 100,
                                          message: '调整原因不能超过100个字',
                                          trigger: 'blur',
                                      },
                                  ]
                        "
                    >
                        <el-input
                            v-model="form.reason"
                            type="textarea"
                            :rows="5"
                        />
                    </el-form-item>
                </el-col>
            </el-card>
        </el-form>

        <userTableDialog
            title="用户"
            :defaultParams="defaultParams"
            :open.sync="showTableVision"
            @confirm="setFormBase"
        >
        </userTableDialog>
    </div>
</template>

<script>
import FlowInfo from "@/views/workflow/flow/flowInfo";
import {
    listPostChange,
    getPostChange,
    delPostChange,
    addPostChange,
    updatePostChange,
} from "@/api/hrm/postChange";
import FormTopBar from "@/views/workflow/common/formTopBar";
import SelectOneUser from "@/views/common/selectUser/selectOneUser";
import { listPostAll, listPost } from "@/api/system/post";
import { getUser } from "@/api/system/user";
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { buildEntryKey } from "@fullcalendar/core/internal";
import { readonly } from "vue";

export default {
    name: "PostChangeForm",
    dicts: [
        "duty_leave_type",
        "sys_user_sex",
        "job_category",
        "hrm_staff_type",
    ],
    components: { FlowInfo, FormTopBar, SelectOneUser, Treeselect },
    data() {
        return {
            postOptions2: [],
            title: "",
            // 表单参数
            form: { changerNickName: "" },
            showFlowInfo: false,
            taskId: "",
            readonly: false,
            showSelectOneUser: false,
            // 职位选项
            postOptions: [],
            // 表单校验
            rules: {
                afterPostIdArr: [
                    {
                        required: true,
                        message: "调整后岗位不能为空",
                        trigger: "change",
                    },
                ],
                changerNickName: [
                    {
                        required: true,
                        message: "姓名不能为空",
                        trigger: "change",
                    },
                ],
                submitTime: [
                    {
                        required: true,
                        message: "调整日期不能为空",
                        trigger: "change",
                    },
                ],
                afterDeptId: [
                    {
                        required: true,
                        message: "调后部门不能为空",
                        trigger: "change",
                    },
                ],
                postTypeCode: [
                    {
                        required: true,
                        message: "岗位类别不能为空",
                        trigger: "change",
                    },
                ],
                afterPostId: [
                    {
                        required: true,
                        message: "调整后岗位不能为空",
                        trigger: "change",
                    },
                ],
                reason: [
                    //限制在100字之内
                ],
            },
            showCommitDialog: false,
            commitType: "",
            defaultParams: {
                isLink: true,
                staffTypes:
                    this.$store.getters.allDefectObj["HR-WEB-061"] == 1
                        ? "1,4"
                        : "1,2,3,4",
            },
            showTableVision: false,

            deptOptions: [],
        };
    },

    computed: {
        topTitle() {
            return this.$route.query.readonly
                ? "查看调岗信息"
                : this.$route.params.formId
                ? "修改调岗信息"
                : "岗位调整";
        },
    },
    provide() {
        return {
            addCcedList: this.addCcedList,
        };
    },
    created() {
        this.getPostData();
        //单据的id主键
        const formId = this.$route.params && this.$route.params.formId;
        //单据的类型
        const billType = this.$route.params && this.$route.params.billType;
        const taskId = this.$route.query && this.$route.query.taskId;
        const readonly = this.$route.query && this.$route.query.readonly;
        if (billType) {
            this.form.billType = billType;
        }
        if (taskId) {
            this.taskId = taskId;
        }
        if ("1" == readonly) {
            this.readonly = true;
        }
        if (formId) {
            this.form.id = formId;
            this.getDetailData(formId);
        }
        this.getTreeselect();
    },
    mounted() {},
    /** 转换部门数据结构 */
    normalizer(node) {
        if (node.children && !node.children.length) {
            delete node.children;
        }
        return {
            id: node.deptId,
            label: node.deptName,
            children: node.children,
        };
    },
    methods: {
        /** 查询部门下拉树结构 */
        getTreeselect() {
            treeselect().then((response) => {
                this.deptOptions = response.data;
            });
        },
        //设置用户
        setFormBase(row) {
            this.form.changerUserId = row.userId;
            this.form.changerNickName = row.realName;
            this.$set(this.form, "changerNickName", row.realName);
            this.form.userId = row.userId;
            this.form.realName = row.realName;
            this.form.sex = row.sex || 0;
            this.form.staffNum = row.staffNum;
            this.form.birthdate = row.birthdate;
            this.form.staffType = String(row.staffType);
            this.form.beforeDeptId = row.deptId;
            this.form.beforePostId = String(row.postId);
            this.$set(this.form, "beforePostId", Number(row.postId));
            this.$refs["form"].clearValidate();
        },
        //  获取单据信息
        getDetailData(id) {
            getPostChange(id).then((response) => {
                this.form = response.data;

                if (this.form.postTypeCode) {
                    this.getPostData2(this.form.postTypeCode);
                }
                this.form.beforeDeptId = Number(this.form.beforeDeptId);
                this.form.afterDeptId = Number(this.form.afterDeptId);
                this.form.beforePostId = Number(this.form.beforePostId);
                this.form.afterPostId = Number(this.form.afterPostId);

                if (this.readonly && !this.form.reason) {
                    this.form.reason = "—";
                }

                this.$forceUpdate();
            });
        },
        getPostData() {
            //清空岗位名称

            this.postIds = [];
            listPost({
                pageSize: 100,
            }).then((res) => {
                this.postOptions = res.rows;
            });
        },
        getPostData2(key) {
            //清空岗位名称

            this.postIds = [];
            listPost({
                pageSize: 100,
                postTypeCode: key,
            }).then((res) => {
                this.postOptions2 = res.rows;
            });
        },

        openSecelctOneUser() {
            this.showTableVision = true;

            // this.showSelectOneUser = true;
            // this.$refs["form"].clearValidate();
        },
        //选择完一条用户
        selectedOneUser(user) {
            // console.log("选择一条用户："+user)
            this.form.changerUserId = user.userId;
            this.form.changerNickName = user.nickName;
            this.$set(this.form, "changerNickName", user.nickName);
            this.showSelectOneUser = false;
            getUser(user.userId).then((response) => {
                console.log("选择的用户详细信息");
                console.log(response);
                this.form.beforePostIdArr = [];
                if (response.postIds) {
                    this.form.beforePostIdArr = response.postIds;
                }
                console.log(this.form.beforePostIdArr);
                this.$forceUpdate();
            });
        },
        // 关闭选择一个用户弹窗
        closeSelectOneUser() {
            this.showSelectOneUser = false;
        },
        /** 提交按钮 */
        submitForm() {
            console.log(this.timeRange);
            // this.form.beforePostId = this.form.beforePostIdArr.join(",");
            // this.form.afterPostId = this.form.afterPostIdArr.join(",");
            // let beforeNameArr = [];
            // let afterNameArr = [];
            // this.postOptions.forEach((item, index) => {
            //     if (this.form.beforePostIdArr.length > 0) {
            //         this.form.beforePostIdArr.forEach((id) => {
            //             if (id === item.postId) {
            //                 beforeNameArr.push(item.postName);
            //             }
            //         });
            //     }
            //     if (this.form.afterPostIdArr.length > 0) {
            //         this.form.afterPostIdArr.forEach((id) => {
            //             if (id === item.postId) {
            //                 afterNameArr.push(item.postName);
            //             }
            //         });
            //     }
            // });
            // this.form.beforePostName = beforeNameArr.join(",");
            // this.form.afterPostName = afterNameArr.join(",");
            this.$refs["form"].clearValidate();
            this.$refs["form"].validate((valid) => {
                if (this.form.reason && this.form.reason.length > 100) {
                    return;
                }

                if (valid) {
                    if (this.form.id != null) {
                        updatePostChange(this.form).then((response) => {
                            this.$modal.msgSuccess("修改成功");
                            this.$router.go(-1);
                        });
                    } else {
                        addPostChange(this.form).then((response) => {
                            this.$modal.msgSuccess("保存成功");
                            this.$router.go(-1);
                        });
                    }
                }
            });
        },
        closeThisPage() {
            this.$tab.closeOpenPage({
                path: "/hrm/changePost/postChange",
                query: { billType: this.form.billType },
            });
        },
        // 创建单据时候，选择了抄送人
        addCcedList(ccedList) {
            this.form.ccedList = ccedList;
            console.log("回填抄送人");
            console.log(this.form);
        },
    },
};
</script>
<style lang="scss" scoped></style>
